#ifndef __CLIENT_REQUEST_SYNC_included
#define __CLIENT_REQUEST_SYNC_included

#include "ClientRequest.h"
#include "Task.h"

using namespace Engine;

class CRequestSync : public CClientRequest {

public :
	CRequestSync() : CClientRequest(string(COMMAND_SYNC)) 
	{ }

	CRequestSync(boost::asio::streambuf& data) :
		CClientRequest(string(COMMAND_SYNC), data)
	{
	}

	virtual void DoRequest() {
		
		string s;
		GetContentAsString(s);
		DebugStream << "CRequestSync::DoRequest - " << s << '\n';

		TableRef tvt = CVersionTag::GetSerializedTable(s);
		if(tvt->GetCount() == 0) return;

		boost::shared_array<RecordRef> recs = tvt->NextRecords(tvt->GetCount());
		int count = tvt->GetCurrentRecordsCount();

		for(int i = 0; i < count; i++) {
			VersionTagRef vt = boost::dynamic_pointer_cast<CVersionTag, CRecord>(recs[i]);
			VersionTagRef local_vt = CVersionTag::QueryDeviceTag(vt->mDevice, vt->mTagName);
			if(!local_vt || local_vt->mHeadVersion < vt->mHeadVersion) {
				TaskRef t = CTaskFactory::Create(vt);
				mConnection->AddTask(t);
			}
		}

		Response(RESPONSE_STATUS_OK);
	}

};

#endif //__CLIENT_REQUEST_SYNC_included